const express = require('express')
const router = express.Router()
const pool = require('../db')
const utility = require('utility')
const jwt = require('jsonwebtoken')

// 注册
router.post('/reguser', (req, res) => {
  req.body.password = utility.md5('cy' + req.body.password + 'nx')
  pool.query('insert into user set ?', req.body, (err, results) => {
    if (err) {
      console.log('err:', err)
      return res.send({
        status: 1,
        message: '用户名已存在',
      })
    }
    console.log(results)
    if (results.affectedRows === 1) {
      res.send({
        status: 0,
        message: '注册成功',
      })
    } else {
      res.send({
        status: 1,
        message: '注册失败',
      })
    }
  })
})

// 登录
router.post('/login', (req, res) => {
  // 根据用户名和密码查询数据库，判断是否存在
  // 如果正确，生成token返回
  let { username, password } = req.body
  password = utility.md5('cy' + password + 'nx')
  pool.query(
    'select * from user where username = ? and password = ?',
    [username, password],
    (err, results) => {
      if (err) {
        return res.send({
          status: 1,
          message: '登录失败',
        })
      }
      // console.log(results)  // 数组
      if (results.length > 0) {
        res.send({
          status: 0,
          message: '登录成功',
          token:
            'Bearer ' +
            jwt.sign({ username }, 'big-event', { expiresIn: '24h' }),
        })
      } else {
        res.send({
          status: 1,
          message: '用户名或密码错误',
        })
      }
    }
  )
})

module.exports = router
